package handler

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"kuangstudy-mall/srvs/userrelation-srv/global"
	"kuangstudy-mall/srvs/userrelation-srv/model"
	"kuangstudy-mall/srvs/userrelation-srv/proto"
)

// 用户收货地址查询
func (handler *UserRelationHandler) FindUserAddressList(ctx context.Context, req *proto.DefaultRequest) (*proto.AddressListResponse, error) {
	var userAddress []model.UserAddress
	var response proto.AddressListResponse
	if result := global.DB.Where(&model.UserAddress{UserId: req.UserId}).Order("default_flag desc").Find(&userAddress); result.RowsAffected != 0 {
		response.Total = int32(result.RowsAffected)
	}
	for _, address := range userAddress {
		response.Data = append(response.Data, &proto.AddressResponse{
			Id:          address.ID,
			UserId:      address.UserId,
			Province:    address.Province,
			City:        address.City,
			District:    address.District,
			Address:     address.Address,
			Username:    address.Username,
			Mobile:      address.Mobile,
			DefaultFlag: address.DefaultFlag,
		})
	}

	return &response, nil
}

// 保存用户收货地址
func (handler *UserRelationHandler) CreateUserAddress(ctx context.Context, req *proto.AddressRequest) (*proto.AddressResponse, error) {
	var address model.UserAddress
	address.ID = req.Id
	address.UserId = req.UserId
	address.Province = req.Province
	address.City = req.City
	address.District = req.District
	address.Username = req.Username
	address.Mobile = req.Mobile
	address.DefaultFlag = req.DefaultFlag
	if req.DefaultFlag {
		// 把其它的默认地址修改成为0
		global.DB.Select("default_flag").Where("user_id = ?", req.UserId).Updates(&model.UserAddress{DefaultFlag: false})
	}
	global.DB.Save(&address)
	return &proto.AddressResponse{
		Id:          address.ID,
		UserId:      address.UserId,
		Province:    address.Province,
		City:        address.City,
		District:    address.District,
		Address:     address.Address,
		Username:    address.Username,
		Mobile:      address.Mobile,
		DefaultFlag: address.DefaultFlag,
	}, nil
}

// 更新收货地址
func (handler *UserRelationHandler) UpdateUserAddress(ctx context.Context, req *proto.AddressRequest) (*emptypb.Empty, error) {
	var address model.UserAddress
	if result := global.DB.Where("id = ? and user_id = ?", req.Id, req.UserId).First(&address); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "收货地址不存在!")
	}
	if req.Province != "" {
		address.Province = req.Province
	}
	if req.City != "" {
		address.City = req.City
	}
	if req.District != "" {
		address.District = req.District
	}
	if req.Username != "" {
		address.Username = req.Username
	}
	if req.Mobile != "" {
		address.Mobile = req.Mobile
	}

	address.DefaultFlag = req.DefaultFlag
	if req.DefaultFlag {
		// 把其它的默认地址修改成为0
		global.DB.Select("default_flag").Where("user_id = ?", req.UserId).Updates(&model.UserAddress{DefaultFlag: false})
	}

	global.DB.Save(&address)
	return &emptypb.Empty{}, nil
}

// 删除收货地址
func (handler *UserRelationHandler) DeleteUserAddress(ctx context.Context, req *proto.DeletetRequest) (*emptypb.Empty, error) {
	if result := global.DB.Unscoped().Where("id = ? and user_id = ?", req.Id, req.UserId).Delete(&model.UserAddress{}); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "收货地址不存在!")
	}
	return &emptypb.Empty{}, nil
}

// 获取默认收货地址
func (handler *UserRelationHandler) GetUserAddressByDefault(ctx context.Context, req *proto.DefaultRequest) (*proto.AddressResponse, error) {
	var address model.UserAddress
	if result := global.DB.Where("user_id = ? and default_flag = 1", req.UserId).First(&address); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "默认收货地址不存在!")
	}
	return &proto.AddressResponse{
		Id:          address.ID,
		UserId:      address.UserId,
		Province:    address.Province,
		City:        address.City,
		District:    address.District,
		Address:     address.Address,
		Username:    address.Username,
		Mobile:      address.Mobile,
		DefaultFlag: address.DefaultFlag,
	}, nil
}

// 设置默认收货地址
func (handler *UserRelationHandler) SettingUserAddressByDefault(ctx context.Context, req *proto.SettingDefaultRequest) (*emptypb.Empty, error) {
	var address model.UserAddress
	if result := global.DB.Where("id = ? and user_id = ?", req.Id, req.UserId).First(&address); result.RowsAffected == 0 {
		return nil, status.Errorf(codes.NotFound, "收货地址不存在!")
	}

	// 把其它的默认地址修改成为0
	global.DB.Select("default_flag").Where("user_id = ?", req.UserId).Updates(model.UserAddress{DefaultFlag: false})
	global.DB.Select("default_flag").Where("id=? and user_id = ?", req.Id, req.UserId).Updates(model.UserAddress{DefaultFlag: true})
	return &emptypb.Empty{}, nil
}
